package gu.sql2java.excel.json;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.gitee.l0km.com4j.base.Pair;
import com.gitee.l0km.com4j.basex.cache.FunctionCached;
import com.google.common.base.Throwables;

/**
 * JSON类型字段使用jJackson自定义反序列化器实现的数据导入适配器实现
 * @author guyadong
 * @since 3.29.0
 */
@SuppressWarnings("rawtypes")
public class JacksonDeserializeHandler extends BaseJsonDeserializeHandler<JsonDeserializer> {
	public JacksonDeserializeHandler() {
		super();
	}
	public <T>JacksonDeserializeHandler(JsonDeserializer<T> initDeserializer, Class<T> initType, T initEmptyValue) {
		super(initDeserializer, initType, initEmptyValue);
	}
	@SuppressWarnings({ "unchecked" })
	private static final
	FunctionCached<Pair<Class, JsonDeserializer>,ObjectMapper> 
	MAPPER_CACHE = FunctionCached.of(c->{
		try {
			ObjectMapper mapper = new ObjectMapper();
	        //通过simpleModule进行注册
	        SimpleModule simpleModule=new SimpleModule();
	        simpleModule.addDeserializer(c.left, c.right);
	        //注册simpleModule
	        mapper.registerModule(simpleModule);
	        return mapper;
		} catch (Exception e) {
			Throwables.throwIfUnchecked(e);
			throw new RuntimeException(e);
		} 
	});

	@SuppressWarnings({ "unchecked" })
	protected Object deserialize(String value,JsonDeserializer deserializer,Class type) {
		 try {
			return MAPPER_CACHE.get(Pair.of(type, deserializer)).readValue(value,type);
		} catch (Exception e) {
			Throwables.throwIfUnchecked(e);
			throw new RuntimeException(e);
		} 
	}
}
